package com.wangjw.tuling.nio.buffers;

import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * Created by wangjianwen on 2018/12/5.
 */
public class SliceBuffer {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); ++i) {
            buffer.put((byte) i);
        }
        printBuffer(buffer);

        buffer.position(3);
        buffer.limit(7);
        printBuffer(buffer);

        ByteBuffer slice = buffer.slice();
        for (int i = 0; i < slice.capacity(); ++i) {
            byte b = slice.get(i);
            b *= 11;
            slice.put(1, b);
        }
        printBuffer(slice);

        buffer.position(0);
        buffer.limit(buffer.capacity());
        printBuffer(buffer);

        while (buffer.remaining() > 0) {
            System.out.print(buffer.get() + " ");
        }
    }

    private static void printBuffer(Buffer buffer) {
        System.out.println("[limit=" + buffer.limit()
                + ", position = " + buffer.position()
                + ", capacity = " + buffer.capacity()
                + ", array = " + buffer.toString() + "]");
    }
}
